public class PrimeNumbers {
    public static void main(String[] args) {
        int n = 20000;
        boolean[] isPrime = new boolean[n + 1];

        // Initialize: assume all numbers are prime initially
        for (int i = 2; i <= n; i++) {
            isPrime[i] = true;
        }

        // Sieve of Eratosthenes
        for (int p = 2; p * p <= n; p++) {
            // If isPrime[p] is not changed, then it is a prime
            if (isPrime[p]) {
                // Mark all multiples of p as non-prime
                // Start from p*p, since smaller multiples are already marked
                for (int multiple = p * p; multiple <= n; multiple += p) {
                    isPrime[multiple] = false;
                }
            }
        }

        // Print primes, 5 per line
        int count = 0;
        System.out.println("Primes between 1 and 20000:");
        for (int i = 2; i <= n; i++) {
            if (isPrime[i]) {
                System.out.printf("%6d", i); // Format output
                count++;
                if (count % 5 == 0) {
                    System.out.println(); // New line after every 5 primes
                }
            }
        }
    }
}